import { Observable } from 'rxjs/Observable';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ElasticsearchService } from './../../services/elasticsearch.service';
import { RestService } from '../../services/rest.service';
import { DataService } from './../../services/data.service';

import * as _ from 'lodash';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  Line1VoltCur: any;
  Line2Temp: any;
  Line3Pre: any;
  Line4VoltCur: any;
  Line5Concent: any;
  Line6ElectConduct: any;
  Line7H2Pre: any;

  selectedTrain: string;
  maxNumber: string;
  queryIP = false;
  routineInterval;

  fromTime;
  toTime;

  constructor(public elastic: ElasticsearchService,
              public dataService: DataService,
              public restService: RestService) {
    this.selectedTrain = '列车001';
    this.maxNumber = '200';
    this.restService.setChartQueryMode(false);
    this.Line1VoltCur = this.restService.getTable('VoltCur');
    this.Line2Temp = this.restService.getTable('Coolant_Temp2');
    this.Line3Pre = this.restService.getTable('Inlet_Pre3');
    this.Line4VoltCur = this.restService.getTable('VoltCur4');
    this.Line5Concent = this.restService.getTable('H2Concent5');
    this.Line6ElectConduct = this.restService.getTable('Electric_conduct6');
    this.Line7H2Pre = this.restService.getTable('H2_Sys_Pre7');
  }

  fromChange(event) {
    this.fromTime = event.value.getTime();
  }

  toChange(event) {
    this.toTime = new Date(event.value).setHours(23, 59, 59, 999);
  }

  query(event) {
    if (!this.fromTime) {
      this.restService.openErrorDialog('请设置开始时间！');
      return;
    }

    this.queryIP = true;
    this.restService.setChartQueryMode(true);
    this.dataService.updateData('RefreshChart');

    const current = new Date().getTime();
    if (!this.toTime || this.toTime < this.fromTime || this.toTime > current) {
      this.toTime = current;
    }

    const delta = Math.round((this.toTime - this.fromTime) / _.toNumber(this.maxNumber));
    console.log('delta = ' + delta);
    this.getBatch(this.fromTime, delta);
  }

  getBatch(fromTime, delta) {
    const observableBatch = [];
    for (let i = 0; i < _.toNumber(this.maxNumber); i++) {
      const currentFrom = fromTime + i * delta;
      observableBatch.push(this.elastic.getLastRecordsFromTo(currentFrom, currentFrom + delta));
    }

    const result = [];
    Observable.forkJoin(observableBatch).subscribe(data => {
      for (let i = 0; i < _.toNumber(this.maxNumber); i++) {
        const item = data[i];
        if (item && item['hits'] && item['hits']['hits']) {
          const itemData = item['hits']['hits'];
          if (!_.isEmpty(itemData)) {
            result.push(itemData[0]);
          }
        }
      }

      this.dataService.updateTrendData({data: result});
      this.queryIP = false;
    }, error => {
      this.queryIP = false;
    });
  }

  routine() {
    if (this.restService.getChartQueryMode()) {
      return;
    }

    this.elastic.getLatestRecords(600, input => {
      if (this.restService.getChartQueryMode()) {
        return;
      }

      this.dataService.updateTrendData(input);

      setTimeout(() => {
        this.routine();
      }, 5 * 1000);
    });
  }

  ngOnInit() {
    this.routine();
  }
}
